package com.cuit.blog.filter;

import org.springframework.util.AntPathMatcher;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(filterName = "RedirectFilter", urlPatterns = "/*")
public class RedirectFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String[] allowedUrls = { "/login", "/user/login", "/css/**", "/js/**", "/image/**", "/index" };

        if (isAllowedUrl(requestURI, allowedUrls) || isAuthenticated(request)) {
            filterChain.doFilter(request, response);
        } else {

            String homePage = (String) request.getSession().getAttribute("homePage");
            if (homePage != null && !requestURI.equals(homePage)) {
                response.sendRedirect(homePage);
            } else {

                response.sendRedirect("/login");
            }
        }
    }

    private boolean isAllowedUrl(String requestURI, String[] allowedUrls) {
        for (String allowedUrl : allowedUrls) {
            if (PATH_MATCHER.match(allowedUrl, requestURI)) {
                return true;
            }
        }
        return false;
    }

    private boolean isAuthenticated(HttpServletRequest request) {
        return request.getSession().getAttribute("username") != null;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
